﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ProductCollector {
    public class WayfairSearcher : ISiteSearcher
    {
        private const string SEARCH_URL = "http://www.wayfair.com/keyword.php?keyword={0}&command=dosearch&curpage={1}";

        private const string NO_IMAGE = "http://img2.wfrcdn.com/lf/79/hash/default/m0/1/no-image.jpg";

        private const string HOME_URL = "http://www.wayfair.com/";
        public IList<Product> Search(SearchCriteria criteria) {
            var web = new HtmlWeb();
            string url = string.Format(SEARCH_URL, criteria.SearchValue, criteria.CurrentPageIndex);
            List<Product> result = new List<Product>();

            HtmlDocument doc = web.Load(url);
            var gridNode = doc.DocumentNode.SelectSingleNode("//ul[@id='sbprodgrid']");
            if (gridNode == null)
            {
                return result;
            }
            var allProds = gridNode.SelectNodes("./li[contains(@class,'productbox') and contains(@class,'large_images')]");
            
            foreach (HtmlNode node in allProds)
            {
                Product p = GetProductByNode(node);
                if(p!=null)
                {
                    result.Add(p);
                }
                if(result.Count >= criteria.NumOfProduct)
                {
                    break;
                }
            }
            return result;
        }
        private Product GetProductByNode(HtmlNode liNode)
        {
            Product p = new Product();
            var atopLink = liNode.SelectSingleNode("./div/div/a[contains(@class,'toplink')]");
            if(atopLink != null)
            {
                p.OriginalUrl = atopLink.GetAttributeValue("href", HOME_URL);
                var img = atopLink.SelectSingleNode("./img");
                if(img != null)
                {
                    p.ThumbImg = img.GetAttributeValue("src",NO_IMAGE);
                }
            }
            var title = liNode.SelectSingleNode("./div/div/a[contains(@class,'toplink')]/div[contains(@class,'prodname')]");
            if(title != null)
            {
                p.ProductName = title.InnerText;
            }
            var price = liNode.SelectSingleNode("./div/div[contains(@class,'pricing_wrap')]/a/div[contains(@class,'price')]");
            if(price!= null)
            {
                p.FormattedPrice = price.InnerText;
            }

            return p;
        }

        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
